package com.tous.modules.config;

import com.tous.modules.handler.UdpServerHandler;
import com.tous.modules.handler.UdpServerHealthIndicator;
import com.tous.modules.service.UdpServer;

import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.handler.codec.http.HttpServerCodec;
import jakarta.annotation.Resource;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author mengwei
 * @description UdpServerConfig
 * @createDate 2025/7/16 15:34
 */
@Configuration
public class UdpServerConfig {


    @Bean(destroyMethod = "shutdownGracefully")
    public EventLoopGroup group() {
        return new NioEventLoopGroup();
    }

    @Bean
    public MeterRegistry meterRegistry() {
        return new SimpleMeterRegistry();
    }


    @Bean
    public UdpServerHandler udpServerHandler(MeterRegistry meterRegistry) {
        return new UdpServerHandler(meterRegistry);
    }

    @Bean
    public HealthIndicator udpServerHealthIndicator(UdpServer udpServer) {
        return new UdpServerHealthIndicator(udpServer);
    }



    @Bean
    public Bootstrap udpBootstrap(EventLoopGroup group, UdpServerHandler handler) {
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new ChannelInitializer<DatagramChannel>() {
                    @Override
                    public void initChannel(DatagramChannel ch) throws Exception {
//                        ch.pipeline().addLast(new UdpMsgProtobufDecoder());
//                        ch.pipeline().addLast(new UdpMsgProtobufEncoder());
                        ch.pipeline().addLast(handler);
                    }
                });
        return b;
    }


    @Bean(destroyMethod = "stop")
    public UdpServer udpServer(Bootstrap bootstrap, EventLoopGroup group) {

        return new UdpServer(bootstrap, group);
    }
}
